<template>
  <div class="sale-contract-details">
    <div class="details-header">
      <h4>销售明细</h4>
      <Button type="primary" @click="addDetail" :disabled="props.disabled" v-if="props.showActions">
        <template #icon>
          <PlusOutlined />
        </template>
        添加商品
      </Button>
    </div>
    
    <div class="details-list">
      <div 
        v-for="(detail, index) in details" 
        :key="detail.id || index"
        class="detail-item"
      >
        <div class="detail-header" >
          <span class="detail-title" v-if="props.showActions">商品{{ index + 1 }}</span>
          <div class="detail-actions" v-if="props.showActions">
            <Button 
              size="small" 
              type="text" 
              @click="copyDetail(index)"
              title="复制"
              :disabled="props.disabled"
            >
              <CopyOutlined />
            </Button>
            <Button 
              size="small" 
              type="text" 
              danger
              @click="removeDetail(index)"
              title="删除"
              :disabled="props.disabled || details.length <= 1"
            >
              <DeleteOutlined />
            </Button>
          </div>

          <span class="detail-title" v-if="detail.orderNo"><b>订单号：{{ detail.orderNo }}</b></span>
          <div class="detail-actions" v-if="detail.customerName">
            <span class="detail-title"><b>{{ detail.customerName }}</b></span>
          </div>
        </div>
        <div>
          
        </div>
        <Row :gutter="16" class="detail-form">
          <Col :span="8">
            <FormItem 
              :label="'品牌'"
            >
              <Select
                v-model:value="detail.brandId"
                placeholder="请选择品牌"
                :options="brandOptions"
                :loading="brandLoading"
                :disabled="props.disabled"
                show-search
                :filter-option="filterOption"
                @change="onBrandChange(index)"
                :getPopupContainer="getPopupContainer"
              />
            </FormItem>
          </Col>
          
          <Col :span="8">
            <FormItem 
              :label="'SPU'"
            >
              <Select
                v-model:value="detail.spuId"
                placeholder="请先选择品牌"
                :options="spuOptionsMap[index] || []"
                :loading="spuLoadingMap[index]"
                :disabled="props.disabled || !detail.brandId"
                show-search
                :filter-option="filterOption"
                @change="onSpuChange(index)"
                :getPopupContainer="getPopupContainer"
              />
            </FormItem>
          </Col>
          
          <Col :span="8">
            <FormItem 
              :label="'SKU'"
            >
              <Select
                v-model:value="detail.skuId"
                placeholder="请先选择SPU"
                :options="skuOptionsMap[index] || []"
                :loading="skuLoadingMap[index]"
                :disabled="props.disabled || !detail.spuId"
                show-search
                :filter-option="filterOption"
                :getPopupContainer="getPopupContainer"
              />
            </FormItem>
          </Col>
        </Row>
        
        <Row :gutter="16" class="detail-form">
          <Col :span="24">
            <FormItem 
              :label="'其他'" 
              :label-col="{ span: 0 }"
              :wrapper-col="{ span: 22 }"
              :name="['details', index, 'others']"
            >
              <Textarea
                v-model:value="detail.others"
                placeholder="请输入其他信息"
                :rows="3"
                :disabled="props.disabled"
              />
            </FormItem>
          </Col>
          
        
        </Row>
        <Row :gutter="16" class="detail-form">
          <Col :span="6">
            <FormItem 
              :label="'售价'" 
            >
              <InputNumber
                v-model:value="detail.amount"
                placeholder="请输入售价"
                :min="0"
                :precision="3"
                :disabled="props.disabled"
                style="width: 100%"
                :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="value => value!.replace(/\$\s?|(,*)/g, '')"
              />
            </FormItem>
          </Col>
          <Col :span="6"    v-if="props.showPurchaseAmount">
            <FormItem 
              :label="'采购价'" 
            >
              <InputNumber
                v-model:value="detail.purchaseAmount"
                placeholder="请输入采购价"
                :min="0"
                :precision="3"
                :disabled="!props.purchaseAmountEditable"
                style="width: 100%"
                :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="value => value!.replace(/\$\s?|(,*)/g, '')"
              />
            </FormItem>
          </Col>
          <Col :span="12" v-if="props.showFrameNo">
            <FormItem 
              :label="'车架号'" 
            >
              <Input
                 v-model:value="detail.frameNo"
                 placeholder="请输入车架号"
                 :disabled="!props.frameNoEditable"
                 style="width: 100%"
               />
            </FormItem>
          </Col>
        </Row>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue';
import { 
  Button, 
  Row, 
  Col, 
  FormItem, 
  Select, 
  Textarea, 
  InputNumber,
  Input 
} from 'ant-design-vue';
import { 
  PlusOutlined, 
  DeleteOutlined, 
  CopyOutlined 
} from '@ant-design/icons-vue';
import { getPopupContainer } from '@vben/utils';
import type { SaleContractDetailVO } from '#/api/trade/saleContract/model';
import { brandList } from '#/api/trade/brand';
import { spuList } from '#/api/trade/spu';
import { skuList } from '#/api/trade/sku';
import type { DefaultOptionType } from 'ant-design-vue/es/select';

interface Props {
  modelValue: SaleContractDetailVO[];
  disabled?: boolean;
  showActions?: boolean;
  showFrameNo?: boolean;
  frameNoEditable?: boolean;
  showPurchaseAmount?: boolean;
  purchaseAmountEditable?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  showActions: true,
  showFrameNo: false,
  frameNoEditable: true,
  showPurchaseAmount: false,
  purchaseAmountEditable: false,
});

interface Emits {
  (e: 'update:modelValue', value: SaleContractDetailVO[]): void;
}
const emit = defineEmits<Emits>();

// 响应式数据
const details = ref<SaleContractDetailVO[]>([]);

// 品牌选项
const brandOptions = ref<DefaultOptionType[]>([]);
const brandLoading = ref(false);

// SPU选项映射（每个明细项对应一个SPU选项列表）
const spuOptionsMap = reactive<Record<number, DefaultOptionType[]>>({});
const spuLoadingMap = reactive<Record<number, boolean>>({});

// SKU选项映射（每个明细项对应一个SKU选项列表）
const skuOptionsMap = reactive<Record<number, DefaultOptionType[]>>({});
const skuLoadingMap = reactive<Record<number, boolean>>({});

// 创建新的明细项
const createNewDetail = (): SaleContractDetailVO => ({
  id: Date.now(), // 临时ID
  brandId: '',
  spuId: '',
  skuId: '',
  others: '',
  amount: 0,
  frameNo: ''
});

// 添加明细项
const addDetail = () => {
  details.value.push(createNewDetail());
};

// 监听props变化
// 添加初始化级联数据的方法
const initializeCascadeData = async () => {
  for (let i = 0; i < details.value.length; i++) {
    const detail = details.value[i]!;
    
    // 如果有brandId，加载对应的SPU选项
    if (detail.brandId) {
      spuLoadingMap[i] = true;
      try {
        const { rows } = await spuList({
          brandId: detail.brandId,
          pageNum: 1,
          pageSize: 200
        });
        spuOptionsMap[i] = rows.map(item => ({
          label: item.spuName,
          value: item.id
        }));
      } finally {
        spuLoadingMap[i] = false;
      }
      
      // 如果有spuId，加载对应的SKU选项
      if (detail.spuId) {
        skuLoadingMap[i] = true;
        try {
          const { rows } = await skuList({
            spuId: detail.spuId,
            pageNum: 1,
            pageSize: 200
          });
          skuOptionsMap[i] = rows.map(item => ({
            label: item.skuName,
            value: item.id
          }));
        } finally {
          skuLoadingMap[i] = false;
        }
      }
    }
  }
};

// 修改监听props变化的逻辑
watch(
  () => props.modelValue,
  async (newValue) => {
    details.value = newValue || [];
    if (details.value.length === 0) {
      addDetail();
    } else {
      // 编辑模式下，初始化级联数据
      await nextTick();
      await initializeCascadeData();
    }
  },
  { immediate: true, deep: true }
);

// 监听details变化，同步到父组件
watch(
  details,
  (newValue) => {
    emit('update:modelValue', newValue);
  },
  { deep: true }
);

// 删除明细项
const removeDetail = (index: number) => {
  if (details.value.length > 1) {
    details.value.splice(index, 1);
    // 清理对应的选项映射
    delete spuOptionsMap[index];
    delete spuLoadingMap[index];
    delete skuOptionsMap[index];
    delete skuLoadingMap[index];
  }
};

// 复制明细项
const copyDetail = (index: number) => {
  const originalDetail = details.value[index];
  const newDetail = {
    ...originalDetail,
    id: Date.now() // 新的临时ID
  };
  details.value.splice(index + 1, 0, newDetail);
  
  // 复制对应的选项数据
  const newIndex = index + 1;
  if (spuOptionsMap[index]) {
    spuOptionsMap[newIndex] = [...spuOptionsMap[index]];
  }
  if (skuOptionsMap[index]) {
    skuOptionsMap[newIndex] = [...skuOptionsMap[index]];
  }
};

// 过滤选项
const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().includes(input.toLowerCase());
};

// 加载品牌列表
const loadBrandOptions = async () => {
  brandLoading.value = true;
  try {
    const { rows } = await brandList({
      pageNum: 1,
      pageSize: 200
    });
    brandOptions.value = rows.map(item => ({
      label: item.brandName,
      value: item.id
    }));
  } finally {
    brandLoading.value = false;
  }
};

// 品牌变化时加载SPU
const onBrandChange = async (index: number) => {
  const detail = details.value[index]!;
  // 清空SPU和SKU
  detail.spuId = '';
  detail.skuId = '';
  delete skuOptionsMap[index];
  
  if (!detail.brandId) {
    delete spuOptionsMap[index];
    return;
  }
  
  spuLoadingMap[index] = true;
  try {
    const { rows } = await spuList({
      brandId: detail.brandId,
      pageNum: 1,
      pageSize: 200
    });
    spuOptionsMap[index] = rows.map(item => ({
      label: item.spuName,
      value: item.id
    }));
  } finally {
    spuLoadingMap[index] = false;
  }
};

// SPU变化时加载SKU
const onSpuChange = async (index: number) => {
  const detail = details.value[index]!;
  // 清空SKU
  detail.skuId = '';
  
  if (!detail.spuId) {
    delete skuOptionsMap[index];
    return;
  }
  
  skuLoadingMap[index] = true;
  try {
    const { rows } = await skuList({
      spuId: detail.spuId,
      pageNum: 1,
      pageSize: 200
    });
    skuOptionsMap[index] = rows.map(item => ({
      label: item.skuName,
      value: item.id
    }));
  } finally {
    skuLoadingMap[index] = false;
  }
};

// 初始化
loadBrandOptions();
</script>

<style scoped>
.sale-contract-details {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  padding: 16px;
  /* background-color: #fafafa; */
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e8e8e8;
}

.details-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.details-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-item {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  padding: 16px;
  position: relative;
  background-color: #fafafa;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-title {
  font-weight: 500;
  color: #595959;
  font-size: 14px;
}

.detail-actions {
  display: flex;
  gap: 4px;
}

.detail-form {
  margin-bottom: 16px;
}

.detail-form:last-child {
  margin-bottom: 0;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-form-item:last-child) {
  margin-bottom: 0;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
}
</style>
